package com.johnson.news.share;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.Window;

import com.johnson.news.event_msg.ShareMsg;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.share.WbShareCallback;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.youmbe.library.util.MyToast;

import org.greenrobot.eventbus.EventBus;

import static com.johnson.news.util.Constants.WEIBO_APP_KEY;
import static com.johnson.news.util.Constants.WEIBO_REDIRECT_URL;
import static com.johnson.news.util.Constants.WEIBO_SCOPE;

public class ShareToWeiBoActivity extends Activity {

    AuthInfo authInfo;
    WbShareHandler shareHandler;

    WebpageObject webpageObject;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Window window = getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0);
        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        webpageObject = getIntent().getParcelableExtra("data");

        authInfo = new AuthInfo(this, WEIBO_APP_KEY, WEIBO_REDIRECT_URL, WEIBO_SCOPE);
        WbSdk.install(this, authInfo);

        shareHandler = new WbShareHandler(this);
        shareHandler.registerApp();

        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        weiboMessage.mediaObject = webpageObject;

        shareHandler.shareMessage(weiboMessage, false);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data.getExtras() == null)//用户未登录时返回，不会回调下边的listener，只能手动关闭
            finish();
        shareHandler.doResultIntent(data,wbShareCallback);
    }

    WbShareCallback wbShareCallback = new WbShareCallback() {
        @Override
        public void onWbShareSuccess() {
            MyToast.showToast("分享成功", ShareToWeiBoActivity.this);
            EventBus.getDefault().post(new ShareMsg(ShareMsg.share_type_wb));
            finish();
        }

        @Override
        public void onWbShareCancel() {
            MyToast.showToast("取消分享", ShareToWeiBoActivity.this);
            finish();

        }

        @Override
        public void onWbShareFail() {
            MyToast.showToast("分享失败", ShareToWeiBoActivity.this);
            finish();

        }
    };
}
